package models

import (
	"hsy/util"
	"reflect"
)

// LoginResponse 登录返回
type LoginResponse struct {
	Token string `json:"token"`
}

// Login 登录
func (u *UserModel) Login(username string, password string) (token string, success bool) {
	row, ok := u.GetOne(username)
	if ok {
		user := reflect.ValueOf(row)
		if util.VerifyPassword(password, user.FieldByName("Password").String()) {
			token := getToken(user.String())
			return token, true
		}
		return "", false
	}
	return "", false
}

// UpdateToken 更新token
func (u *UserModel) UpdateToken(username string, token string) error {
	var user UserModel
	return self.Model(&user).Where("username = ?", username).Update("token", token).Error
}

func getToken(data string) string {
	token, err := util.GenerateToken(data)
	if err != nil {
		return ""
	}
	return token
}
